package ch.fhnw.qualiscan.application.modals;

import java.util.Vector;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.UserModel;
import ch.fhnw.qualiscan.core.Modal;
import ch.fhnw.qualiscan.core.db.fieldfactories.UserFieldFactory;
import ch.fhnw.qualiscan.core.db.pojos.User;
import ch.fhnw.qualiscan.core.helpers.SessionHelper;
import ch.fhnw.qualiscan.core.libraries.NotificationLib;

import com.vaadin.data.Validator;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class AdminEditUser extends Modal {
	
	public Form profileForm;
	public User user;
	
	private UserModel userModel;
	
	public AdminEditUser() {}
	
	public AdminEditUser(int userId) {
		setCaption(TM.get("admin.edit.user.title"));
		
		userModel = new UserModel();
		
		user = (User) hibernateSession.getSession().get(User.class, userId);
		
		addComponent(buildProfileForm());
		addComponent(editPasswordForm());
	}
	
	public Panel buildProfileForm() {
		
		profileForm = new Form();
        BeanItem<User> item = new BeanItem<User>(user);
        
        profileForm.setItemDataSource(item);
        profileForm.setImmediate(true);
        profileForm.setFormFieldFactory(new UserFieldFactory());
        profileForm.setWidth("100%");
        
        Vector<String> order = new Vector<String>();
        order.add("firstname");
        order.add("lastname");
        order.add("email");
        //TODO when multilingual support activated add order.add("language");
        
        profileForm.setVisibleItemProperties(order); 
        
        HorizontalLayout buttonBar = new HorizontalLayout();
        profileForm.getFooter().addComponent(buttonBar);
        Button commit = new Button(TM.get("action.save"), new ClickListener() {
            public void buttonClick(ClickEvent event) {
            	try {
            		profileForm.commit();
            		userModel.updateProfile(user);
            		NotificationLib.showSuccess(TM.get("action.saved"), null);
            	}
            	catch (InvalidValueException e) {
                    return;
            	}      
            }
        });
        commit.setIcon(Config.ICON_SAVE);
        buttonBar.addComponent(commit);
       
        Panel editProfile = new Panel();
		editProfile.addComponent(textHelper.h3(TM.get("admin.edit.user.title")));
		editProfile.addComponent(textHelper.p(TM.get("admin.edit.user.desc", user.getFirstname() + " " + user.getLastname())));
		editProfile.addComponent(profileForm);
        
        return editProfile;
	}
	
	public Panel editPasswordForm() {
		Validator passwordValidator  = new Validator() {
			public void validate(Object value) throws InvalidValueException {
				if(!isValid(value)) {
					if(value.toString().length() < 6) {
						throw new InvalidValueException(TM.get("user.error.password.tooshort"));
					}
					if(value.toString().length() > 16) {
						throw new InvalidValueException(TM.get("user.error.password.toolong"));
					}
				}
			}

			public boolean isValid(Object value) {
				if(value.toString().length() < 6 || value.toString().length() > 16) {
					return false;
				} else {
					return true;
				}
			}
		};

		Panel pwdPanel = new Panel();
		
		VerticalLayout passwordForm = new VerticalLayout();
		passwordForm.setSpacing(true);
		
		passwordForm.addComponent(textHelper.h3(TM.get("admin.edit.password.title")));
		passwordForm.addComponent(textHelper.p(TM.get("admin.edit.password.desc")));

		// password textfield
		final TextField pwd = new TextField();
		pwd.setSecret(true);
		pwd.setInputPrompt(TM.get("profile.password"));
		pwd.setCaption(TM.get("user.password"));
		pwd.addValidator(passwordValidator);
		pwd.setRequired(true);
		pwd.setRequiredError(TM.get("user.error.password"));
		pwd.setImmediate(true);
		
		passwordForm.addComponent(pwd);
		
		Button savePwdButton = new Button(TM.get("action.save"));
		savePwdButton.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				try {
					pwd.validate();
				} catch (InvalidValueException e) {
					pwd.setValidationVisible(true);
				}
				
				if(pwd.isValid()) {
					SessionHelper sessionHelper = new SessionHelper();
					
					if(userModel.updatePassword(user.getId(), pwd.getValue().toString(), true)) {
						NotificationLib.showSuccess(TM.get("admin.password.success"), null);
					} else {
						NotificationLib.showError(TM.get("notification.error.notsaved"), null);
					}
				}
			}
		});
		savePwdButton.setIcon(Config.ICON_SAVE);
		
		passwordForm.addComponent(savePwdButton);
		pwdPanel.addComponent(passwordForm);
		
		return pwdPanel;
	}
	
}
